package org.test;

public abstract class Map {

	private static final int COLISIED_OBJECTS = 5;
	
	private String name;
	private final int width;
	private final int height;
	private MapObject[][][] map;

	protected Map(int width, int height){
		this.width = width;
		this.height = height;
		map = new MapObject[width][height][COLISIED_OBJECTS];
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public synchronized void setObjectOn(MapObject object, int x, int y){
		if (x<0 || x>=width || y<0 || y>=height){
			throw new RuntimeException("Invalid coordinates.");
		}
		MapObject[] objects = map[x][y];
		
		int empty=0;
		for (int i=0;i<objects.length;i++){
			MapObject obj = objects[i];
			if (obj==null){
				empty++;
			}else{
				obj.collision(object);
				object.collision(obj);
			}
		}
		
		int position;
		for (position=0;position<objects.length;position++){ //znalezienie wolnego miejsca
			if (objects[position]==null) break;
		}
		if (position==objects.length){
			rebuild(x,y,objects.length+COLISIED_OBJECTS);
			map[x][y][position] = object;
		}else{
			objects[position] = object;
			if (empty>COLISIED_OBJECTS){
				rebuild(x,y,objects.length-COLISIED_OBJECTS);
			}
		}
	}
	
	private synchronized void rebuild(int x,int y,int newsize){
		MapObject[] objects = map[x][y];
		MapObject[] newobjects = new MapObject[newsize];
		for (int i=0;i<objects.length;i++){
			newobjects[i]=objects[i];
		}
		map[x][y] = newobjects;
	}
	
	
	
}
